<template>
  <publicBgPage>
    <div class="resetBox" solt>
      <div class="backAccountAndCodeLogin">
        <!-- <div class="backLogin" @click="changeBackLogin">返回登录</div>
        <div class="linear" /> -->
        <div class="backAccountLogin" @click="changeBackLogin">
          返回登录
          <img :src="require('@/assets/images/goRegisterIcon.png')" class="goIcon" />
        </div>
      </div>
      <div class="title">重置密码</div>
      <el-form class="apply-form first-form" :model="reset.user" :rules="resestRules" ref="updateUserInfo"
        @submit.native.prevent>
        <el-form-item prop="email" :error="emailErrorMessage">
          <el-input type="text" v-model="reset.user.email" :class="{ haveValue: reset.user.email }" placeholder="请输入邮箱"
            @keypress.enter.native.prevent @change="handleChangeEmail"></el-input>
        </el-form-item>
        <el-form-item prop="code" :error="codeErrorMessage">
          <el-input type="text" placeholder="请输入获取的验证码" v-model="reset.user.code"
            :class="{ haveValue: reset.user.code }" @keypress.enter.native.prevent></el-input>
          <div class="fetchCodeBox">
            <button class="fetchCode" @click.prevent="checkEmailField" tabindex="-1">
              {{ codeLastTime ? codeLastTime + "秒" : "获取验证码" }}
            </button>
          </div>
          <div class="codeTips" v-show="showCodeTips">验证码已发送至邮箱</div>
        </el-form-item>
        <el-form-item prop="password" :error="pwdErrorMessage">
          <el-input type="password" v-model="reset.user.password" :class="{ haveValue: reset.user.password }"
            placeholder="请输入新密码" show-password @keypress.enter.native.prevent></el-input>
        </el-form-item>
        <el-form-item prop="rpassword" class="lastInput">
          <el-input type="password" v-model="reset.user.rpassword" :class="{ haveValue: reset.user.rpassword }"
            placeholder="请确认密码" @keypress.enter.native.prevent></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="loginBtn" :loading="load" @click="verificationValue">确认</el-button>
        </el-form-item>
      </el-form>
    </div>
  </publicBgPage>
</template>


<script>
import publicBgPage from "@/components/publicBgPage/publicBgPage";
import { throttle, location } from "@/util/tool";
import {
  isExist,
  sendVaildCode,
  checkVaildCode,
  updatePasswordByEmail,
} from "@/request/user";
import { mapState } from "vuex";
import md5 from "js-md5";
export default {
  components: {
    publicBgPage,
  },
  data() {
    let pwdReg =
      /(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,20}$/;
    var validatePassword = (rule, value, callback) => {
      if (!pwdReg.test(value)) {
        callback(
          new Error("请输入6-20位，必须包含数字与字母、或符号的有效密码！")
        );
      } else {
        callback();
      }
    };
    var validateRepeatPwd = (rule, value, callback) => {
      if (this.reset.user.password !== value) {
        callback(new Error("两次密码不一致！"));
      } else {
        callback();
      }
    };

    const mailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    var checkEmail = (rule, value, callback) => {
      // 如果已经验证过 邮箱未注册 则返回
      if (this.checkEmail === false) {
        this.emailErrorMessage = "";
        this.$nextTick(() => {
          callback(
            new Error(
              this.errState === 1 ? "邮箱未注册" : "账号验证失败，请重新输入!"
            )
          );
        });
        return;
      }

      if (!mailReg.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };

    return {
      reset: {
        user: {
          regName: "",
          email: "",
          code: "",
          password: "",
          rpassword: "",
        },
      },
      // 重置信息验证
      resestRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            validator: validatePassword,
            trigger: "change",
          },
          {
            validator: validatePassword,
            trigger: "blur",
          },
        ],
        rpassword: [
          {
            required: true,
            message: "确认密码不能为空",
            trigger: "blur",
          },
          {
            validator: validateRepeatPwd,
            trigger: "change",
          },
          {
            validator: validateRepeatPwd,
            trigger: "blur",
          },
        ],
      },
      load: false,
      loging: false,
      codeLastTime: 0,
      showCodeTips: false, // 显示已发送验证码提示
      codeErrorMessage: "", // 验证码错误提示
      routerTimer: null, // 跳转路由定时器
      pwdErrorMessage: "", // 新密码与旧密码相同错误提示
      checkEmail: null,
      errState: 0,
      emailErrorMessage: "",
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  created() {
    this.handleGetLastTime();
  },
  methods: {
    // 设置发送验证码剩余时间
    handleGetLastTime() {
      let sendRegCodeLastTime = localStorage.getItem("rRCLT");
      const currTime = new Date().getTime();
      if (sendRegCodeLastTime === null) {
        this.codeLastTime = 0;
        return;
      }
      if (currTime - sendRegCodeLastTime < 60000) {
        this.handelFetchCode(
          60 - Math.ceil((currTime - sendRegCodeLastTime) / 1000)
        );
      } else {
        localStorage.removeItem("rRCLT");
      }
    },
    // 获取验证码
    handelFetchCode(time) {
      this.showCodeTips = true;
      // 如果验证码已发送倒计时没结束则退出
      this.codeLastTime = time;
      let lassTimer = setInterval(() => {
        --this.codeLastTime;
        // 清除计时器
        if (this.codeLastTime === 0) {
          clearInterval(lassTimer);
          lassTimer = null;
          localStorage.removeItem("rRCLT");
        }
      }, 1000);
    },
    // 验证参数
    verificationValue() {
      this.$refs["updateUserInfo"].validate((valid) => {
        if (valid) {
          this.checkCode();
        } else {
          return false;
        }
      });
    },
    // 更新用户信息
    async update() {
      let uID = await this.getUserInfo({ userName: this.reset.user.email });
      if (uID) uID = uID.userID;
      let params = {
        email: this.reset.user.email,
        validCode: this.reset.user.code,
        newPassword: md5(this.reset.user.password),
      };
      if (!params.newPassword) {
        return this.$antdMessage.error({
          content: "客户端异常,请联系管理员!",
        });
      }
      this.pwdErrorMessage = "";
      updatePasswordByEmail(params).then((res) => {
        if (res.errno === 0) {
          // 清空表单
          this.$refs.updateUserInfo.resetFields();
          this.$antdMessage.success({
            content: "修改成功！3秒后跳到登录页面",
          });
          this.routerTimer = setTimeout(() => {
            this.$router.push({ name: "Login" });
          }, 3000);
        } else if (
          res.errno === 10016 &&
          res.message === "没有需要修改的信息！"
        ) {
          this.pwdErrorMessage = "新密码不能与旧密码相同！";
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 返回登录
    changeBackLogin() {
      this.$router.push({ name: "Login" });
    },
    // 临时获取用户信息
    getUserInfo(data) {
      return new Promise((resvloe, reject) => {
        isExist(data).then((res) => {
          if (res.errno === 0) {
            resvloe(res.data);
          } else {
            this.$antdMessage.error({
              content: res.message,
            });
            reject(false);
          }
        });
      });
    },
    // 验证邮箱字段
    checkEmailField() {
      this.$refs["updateUserInfo"].validateField("email", (res) => {
        this.emailErrorMessage = "";
        if (this.checkEmail === false) {
          this.$nextTick(() => {
            this.emailErrorMessage =
              this.errState === 1
                ? "邮箱已被注册"
                : "账号验证失败，请重新输入!";
          });
        } else {
          // 如果返回的错误信息为空
          if (res === "") {
            this.sendCode();
          }
        }
      });
    },
    // 发送验证码
    sendCode() {
      // // 查看剩余时间
      if (this.codeLastTime) return;
      const params = { userMail: this.reset.user.email, toFindPwd: true };
      sendVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: `验证码已发送至邮箱，验证码有效时间${res.data.duration / 60
              }分钟！`,
          });
          localStorage.setItem("rRCLT", new Date().getTime());
          this.handelFetchCode(60);
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 验证验证码是否正确
    checkCode() {
      // 先清空错误提示 否则多次错误无法显示错误信息
      this.codeErrorMessage = "";
      const params = {
        userMail: this.reset.user.email,
        code: this.reset.user.code,
      };
      checkVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.update();
        } else if (res.message === "验证码已失效！") {
          this.$nextTick(() => {
            this.codeErrorMessage = res.message || "验证码错误";
          });
        } else {
          this.$antdMessage.error({
            content: res.message,
          });
        }
      });
    },
    // 输入邮箱
    handleChangeEmail() {
      this.checkEmail = null;
      // 验证邮箱字段
      this.$refs["updateUserInfo"].validateField("email", (res) => {
        // 如果返回的错误信息为空
        if (res === "") {
          throttle(() => {
            this.emailErrorMessage = "";
            this.errState = 0;
            this.checkAccountNum({
              userName: this.reset.user.email,
            }).then((isPass) => {
              if (isPass === "pass") {
                this.emailErrorMessage = "";
                this.checkEmail = true;
                return;
              }
              if (isPass === "notpass") {
                this.emailErrorMessage = "邮箱未注册";
                this.checkEmail = false;
                this.errState = 1;
              }
              if (isPass === "err") {
                this.emailErrorMessage = "账号验证失败，请重新输入!";
                this.checkEmail = false;
                this.errState = 2;
              }
            });
          });
        }
      });
    },
    // 检查邮箱是否被使用
    checkAccountNum(data) {
      return new Promise((resvloe, reject) => {
        isExist(data)
          .then((res) => {
            if (res.errno !== 0 || res?.message === "用户名未存在") {
              resvloe("notpass");
            } else {
              resvloe("pass");
            }
          })
          .catch((err) => {
            resvloe("err");
          });
      });
    },
  },
  beforeDestroy() {
    clearTimeout(this.routerTimer);
  },
};
</script>

<style lang="stylus">
.resetBox {
  padding: 68px 56px 0 56px;
  margin: 47px auto 0;
  position: relative;
  width: 432px;
  height: 460px;
  background-color: #ffffff;
  border-radius: 5px;
  border: solid 1px #d9d7d7;

  .backAccountAndCodeLogin {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    align-items: center;
    font-family: Segoe UI;
    font-size: 14px;
    color: #0e79c0;

    .linear {
      margin: 0 13px;
      width: 1px;
      height: 16px;
      background: #0e79c0;
      opacity: 0.5;
    }

    .backLogin {
      cursor: pointer;
    }

    .backAccountLogin {
      z-index: 10;
      cursor: pointer;
      display: flex;
      align-items: center;

      .goIcon {
        margin-left: 10px;
        width: 15px;
        height: 15px;
      }
    }
  }

  .title {
    margin-bottom: 35px;
    position: relative;
    text-align: center;
    font-family: Segoe UI;
    font-weight: bold;
    font-size: 20px;
    color: #0e79c0;
  }

  .title:after {
    position: absolute;
    content: '';
    left: 50%;
    right: 50%;
    bottom: -4px;
    width: 20px;
    height: 4px;
    background: #0e79c0;
    border-radius: 8px;
    transform: translate(-50%, 0);
  }

  .el-form {
    .el-form-item {
      margin-bottom: 25px;

      .el-form-item__content {
        line-height: 1;
        position: relative;

        .el-input {
          .el-input__inner {
            background: #ececec;
            border-color: #ececec;
            font-family: Segoe UI;
            font-size: 14px;
            color: #707070;
          }

          .el-input__inner:focus {
            background: #fbf9b8;
          }
        }

        .haveValue {
          .el-input__inner {
            background: #fbf9b8;
          }
        }

        .el-checkbox-group {
          line-height: 1;

          .el-checkbox {
            margin-right: 10px;
            line-height: 1;

            .el-checkbox__label {
              padding-left: 5px;
              font-family: Segoe UI;
              font-size: 14px;
              color: #707070;
              opacity: 0.6;
            }

            .el-checkbox__inner {
              position: relative;
              border-color: #eaeef3;
              background: #eaeef3;
            }

            .el-checkbox__inner::after {
              display: block;
              box-sizing: content-box;
              content: '';
              border: 2px solid #FFF;
              border-left: 0;
              border-top: 0;
              height: 7px;
              left: 4px;
              position: absolute;
              top: 1px;
              transform: rotate(45deg) scaleY(1);
              width: 3px;
              transition: transform 0.15s ease-in 0.05s;
              transform-origin: center;
            }

            .is-checked {
              .el-checkbox__inner {
                border-color: #75c42e;
                background: #75c42e;
              }
            }
          }

          .first-checkBox {
            margin-left: 172px;
          }

          .second-checkBox {
            margin-right: 0;
          }
        }

        .checkBoxTitle {
          position: absolute;
          line-height: 1;
          left: 0;
          top: 0;
          font-family: Segoe UI;
          font-size: 14px;
          color: #707070;
        }

        .loginBtn {
          width: 320px;
          height: 48px;
          background-color: #0e79c0;
          border-radius: 25px;
        }
      }
    }

    .userSelectType {
      margin-bottom: 14px;
    }

    .agreementAndprivacyPolicy {
      margin-bottom: 20px;

      .el-form-item__content {
        .el-checkbox {
          margin-right: 10px;
          line-height: 1;

          .el-checkbox__label {
            padding-left: 5px;
            font-family: Segoe UI;
            font-size: 12px;
            color: #707070;

            .agreementLink {
              font-family: Segoe UI;
              font-size: 12px;
              color: #0e79c0;
            }
          }

          .el-checkbox__inner {
            position: relative;
            border-color: #eaeef3;
            background: #eaeef3;
          }

          .el-checkbox__inner::after {
            display: block;
            box-sizing: content-box;
            content: '';
            border: 2px solid #FFF;
            border-left: 0;
            border-top: 0;
            height: 7px;
            left: 4px;
            position: absolute;
            top: 1px;
            transform: rotate(45deg) scaleY(1);
            width: 3px;
            transition: transform 0.15s ease-in 0.05s;
            transform-origin: center;
          }

          .is-checked {
            .el-checkbox__inner {
              border-color: #75c42e;
              background: #75c42e;
            }
          }
        }
      }
    }

    .lastInput {
      margin-bottom: 20px;
    }
  }

  .fetchCodeBox {
    position: absolute;
    right: 8px;
    top: 10px;
    height: 20px;
    line-height: 20px;

    button {
      cursor: pointer;
      padding: 0;
      padding-left: 6px;
      min-width: 77px;
      text-align: center;
      outline: none;
      height: 20px;
      line-height: 20px;
      border: none;
      border-left: 1px dashed #909090;
      background: transparent;
      font-family: Segoe UI;
      font-size: 14px;
      color: #0e79c0;
      opacity: 0.6;
    }
  }

  .codeTips {
    bottom: -15px;
    position: absolute;
    right: 0;
    font-size: 12px;
    color: #707070;
  }
}
</style>